from flask import request, render_template, jsonify, current_app, g, abort, redirect, url_for

from info import db, constants
from info.libs.image_storage import storage
from info.models import House, HouseImage
from info.modules.house import house_blu
from info.utils.common import user_login
from info.utils.response_code import RET


@house_blu.route('/<house_id>')
@user_login
def get_detail(house_id):
    user = g.user

    try:
        house_id = int(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    if not house:
        return jsonify(errno=RET.NODATA, errmsg='此房不存在')

    # print(house.to_full_dict()['comments'])
    print(house.to_full_dict()['img_urls'])

    data = {
        'house': house.to_full_dict(),
        'user_id': user.id if user else None
    }

    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@house_blu.route('/<house_id>/images', methods=['POST'])
@user_login
def set_image(house_id):
    user = g.user

    if not user:
        return redirect('/login.html')

    try:
        image_file = request.files.get('house_image').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        house_id = int(house_id)
    except Exception as e:
        current_app.logger.error(e)
        jsonify(errno=RET.OK, errmsg='参数错误')

    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    # 上传七牛云
    try:
        key = storage(image_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传头像失败")

    # 将图片添加到 house_image 中
    house_image = HouseImage()
    house_image.house_id = house.id
    house_image.url = key

    # 将最后一个上传的图片作为 主图片
    house.index_image_url = key

    try:
        db.session.add(house_image)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库存储失败')

    data = {
        'url': constants.QINIU_DOMIN_PREFIX + key
    }

    return jsonify(errno=RET.OK, errmsg='上传图片成功', data=data)
